package com.unione.unione_network

import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

object UnioneClient {
    var sOkClientConfig = OkClientConfig()
    private var serviceMap = mutableMapOf<Any, Any>()

    @Volatile
    private var sRetrofit: Retrofit? = null

    /**
     * create api service
     */
    @Suppress("UNCHECKED_CAST")
    @Synchronized
    fun <T : Any> create(service: Class<T>, baseUrl: String): T {
        val serviceInstance = serviceMap[service]
        return if (serviceInstance != null) {
            serviceInstance as T
        } else {
            sRetrofit = getRetrofit(baseUrl)
            val t = getRetrofit(baseUrl).create(service)
            serviceMap[service] = t
            t
        }
    }

    private fun getRetrofit(baseUrl: String): Retrofit {
        if (sRetrofit == null) {
            synchronized(UnioneClient::class.java) {
                if (sRetrofit == null) {
                    sRetrofit = Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .client(OKHttpWrapper.get().client())
                        .addConverterFactory(MoshiConverterFactory.create())
                        .build()
                }
            }
        } else {
            if (!baseUrl.equals(sRetrofit!!.baseUrl())) {
                sRetrofit = sRetrofit!!.newBuilder().baseUrl(baseUrl).build()
            }
        }
        return sRetrofit!!
    }

    private fun getMoshi(): Moshi {
        return Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
    }

    class OkClientConfig {
        val connectionTimeout: Long = 20_000L
        val readTimeout: Long = 20_000L
        val writeTimeout: Long = 20_000L
    }
}